//
//  NextWorkUtil.swift
//  NanChangRER
//
//  Created by Groot on 2017/8/23.
//  Copyright © 2017年 Groot. All rights reserved.
//

import Alamofire
import ObjectMapper

class NetWorkUtil {
    static let shareInstance = NetWorkUtil()
    private init() {
    }
}

extension NetWorkUtil{
    func postForObject<T: Mappable>(objectType type: T.Type,
                                    urlString:String,
                                    parameters:Parameters? = nil,
                                    finishCallBack:@escaping (_ responseObject:T?, _ error:Error?) -> Void,
                                    alreadyRefreshToken: Bool = false,
                                    tokenNeeded: Bool = true){
        // 请求方法
        let method = HTTPMethod.post;
        var headers: [String: String] = [:]
        if tokenNeeded {
            let u = CUserManager.shareInstance.cUser
            headers = ["Authorization": "\(u?.tokenType ?? "") \(u?.accessToken ?? "")"]
        }
        
        Alamofire.request(urlString,
                          method: method,
                          parameters: parameters,
                          headers:headers/*,
                          encoding: JSONEncoding.default*/)
            .responseString(completionHandler: { (res) in
                //print(res.description)
            })
            .responseJSON { (response) in
                if response.result.isSuccess
                {
                    if let value = response.result.value {
                        let resObj = Mapper<T>().map(JSONObject: value)
                        if resObj is BaseResponse {
                            // 401 未授权错误
                            let baseResponse = resObj as! BaseResponse
                            if baseResponse.code == ECode.uncertified.rawValue || baseResponse.code == ECode.other.rawValue
                            // 是否已经刷新过token
                            && !alreadyRefreshToken {
                                // 刷新token
                                CUserManager.shareInstance.refreshToken(block: { [unowned self](b) in
                                    if (b) {
                                        // 刷新完毕重新请求接口
                                        self.postForObject(objectType: type, urlString: urlString, finishCallBack: finishCallBack, alreadyRefreshToken: true)
                                    }else {
                                        // 刷新token 报错了
                                        finishCallBack(resObj, nil)
                                    }
                                })
                                return
                            }
                        }
                        // 如果不需要刷新token 则返回请求结果
                        finishCallBack(resObj, nil)
                    }else {
                        // 请求失败
                        finishCallBack(nil, nil)
                    }
                }
                else
                {
                    finishCallBack(nil,response.result.error)
                }
        }
        
    }
    
    func getForObject<T: Mappable>(objectType type: T.Type,
                                   urlString:String,
                                   parameters:Parameters? = nil,
                                   alreadyRefreshToken: Bool = false,
                                   tokenNeeded: Bool = true,
                                   finishCallBack:@escaping (_ responseObject:T?, _ error:Error?) -> Void){
        
        let method = HTTPMethod.get;
        var headers: [String: String] = [:]
        if tokenNeeded {
            let u = CUserManager.shareInstance.cUser
            headers = ["Authorization": "\(u?.tokenType ?? "") \(u?.accessToken ?? "")"]
        }
        Alamofire.request(urlString,
                          method: method,
                          parameters: parameters,
                          headers:headers)
            .responseJSON { (response) in
                if response.result.isSuccess
                {
                    if let value = response.result.value {
                        let resObj = Mapper<T>().map(JSONObject: value)
                        if resObj is BaseResponse
                            // 401 未授权错误
                            && (resObj as! BaseResponse).code == ECode.uncertified.rawValue
                            // 是否已经刷新过token
                            && !alreadyRefreshToken {
                            // 刷新token
                            CUserManager.shareInstance.refreshToken(block: { [unowned self](b) in
                                if (b) {
                                    // 刷新完毕重新请求接口
                                    self.getForObject(objectType: type, urlString: urlString,  alreadyRefreshToken: true, finishCallBack: finishCallBack)
                                }else {
                                    // 刷新token 报错了
                                    finishCallBack(resObj, nil)
                                }
                            })
                            return
                        }
                        // 如果不需要刷新token 则返回请求结果
                        finishCallBack(resObj, nil)
                    }else {
                        // 请求失败
                        finishCallBack(nil, nil)
                    }
                }
                else
                {
                    finishCallBack(nil,response.result.error)
                }
        }
        
    }
}

        //认证相关设置
//        let manager = SessionManager.default
//        manager.delegate.sessionDidReceiveChallenge = { session, challenge in
//            //认证服务器证书
//            if challenge.protectionSpace.authenticationMethod
//                == NSURLAuthenticationMethodServerTrust {
//                print("服务端证书认证！")
//                let serverTrust:SecTrust = challenge.protectionSpace.serverTrust!
//                let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0)!
//                let remoteCertificateData
//                    = CFBridgingRetain(SecCertificateCopyData(certificate))!
//                let cerPath = Bundle.main.path(forResource: "tomcat", ofType: "cer")!
//                let cerUrl = URL(fileURLWithPath:cerPath)
//                let localCertificateData = try! Data(contentsOf: cerUrl)
//
//                if (remoteCertificateData.isEqual(localCertificateData) == true) {
//
//                    let credential = URLCredential(trust: serverTrust)
//                    challenge.sender?.use(credential, for: challenge)
//                    return (URLSession.AuthChallengeDisposition.useCredential,
//                            URLCredential(trust: challenge.protectionSpace.serverTrust!))
//
//                } else {
//                    return (.cancelAuthenticationChallenge, nil)
//                }
//            }
//                //认证客户端证书
//            else if challenge.protectionSpace.authenticationMethod
//                == NSURLAuthenticationMethodClientCertificate {
//                print("客户端证书认证！")
//                //获取客户端证书相关信息
//                let identityAndTrust:IdentityAndTrust = extractIdentity();
//
//                let urlCredential:URLCredential = URLCredential(
//                    identity: identityAndTrust.identityRef,
//                    certificates: identityAndTrust.certArray as? [AnyObject],
//                    persistence: URLCredential.Persistence.forSession);
//
//                return (.useCredential, urlCredential);
//            }
//                // 其它情况（不接受认证）
//            else {
//                print("其它情况（不接受认证）")
//                return (.cancelAuthenticationChallenge, nil)
//            }
//        }

//
////定义一个结构体，存储认证相关信息
//struct IdentityAndTrust {
//    var identityRef:SecIdentity
//    var trust:SecTrust
//    var certArray:AnyObject
//}
//
////获取客户端证书相关信息
//func extractIdentity() -> IdentityAndTrust {
//    var identityAndTrust:IdentityAndTrust!
//    var securityError:OSStatus = errSecSuccess
//
//    let path: String = Bundle.main.path(forResource: "mykey", ofType: "p12")!
//    let PKCS12Data = NSData(contentsOfFile:path)!
//    let key : NSString = kSecImportExportPassphrase as NSString
//    let options : NSDictionary = [key : "changeit"]
//
//    var items : CFArray?
//
//    securityError = SecPKCS12Import(PKCS12Data, options, &items)
//
//    if securityError == errSecSuccess {
//        let certItems:CFArray = items as CFArray!;
//        let certItemsArray:Array = certItems as Array
//        let dict:AnyObject? = certItemsArray.first;
//        if let certEntry:Dictionary = dict as? Dictionary<String, AnyObject> {
//            // grab the identity
//            let identityPointer:AnyObject? = certEntry["identity"];
//            let secIdentityRef:SecIdentity = identityPointer as! SecIdentity!
//            //print("\(identityPointer)  :::: \(secIdentityRef)")
//            // grab the trust
//            let trustPointer:AnyObject? = certEntry["trust"]
//            let trustRef:SecTrust = trustPointer as! SecTrust
//            //print("\(trustPointer)  :::: \(trustRef)")
//            // grab the cert
//            let chainPointer:AnyObject? = certEntry["chain"]
//            identityAndTrust = IdentityAndTrust(identityRef: secIdentityRef,
//                                                trust: trustRef, certArray:  chainPointer!)
//        }
//    }
//    return identityAndTrust;
//}

